package service.impl;

import mapper.*;
import model.Prescription;
import model.PrescriptionBatchDetail;
import model.PrescriptionDetail;
import model.dto.PrescriptionDto;
import model.vo.PrescriptionVo;
import model.dto.AddPrescriptionDto;
import model.vo.PrescriptionDrugVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import service.PrescriptionService;

import javax.annotation.Resource;
import java.util.List;

@Service
@Transactional
public class PrescriptionServiceImpl implements PrescriptionService {
    @Resource
    private PrescriptionMapper mapper;
    @Resource
    private PrescriptionDetailMapper detailMapper;
    @Resource
    private PrescriptionBatchDetailMapper batchDetailMapper;
    @Resource
    private PrescriptionDrugMapper prescriptionDrugMapper;
    @Resource
    private DrugBatchMapper drugBatchMapper;

    @Override
    public int add(List<AddPrescriptionDto> data) {


        Prescription prescription = new Prescription();
        prescription.setRegistryId(data.get(0).getRid());
        prescription.setPatientId(data.get(0).getPid());
        //总金额=药品价格乘以数量，需要在下面的循环里算出来后更新
        prescription.setFee(100);//暂时写100
        int id = mapper.add(prescription);//添加药方，返回id
        data.forEach((item)->{
            PrescriptionDetail detail = new PrescriptionDetail();//药方明细
            detail.setPrescriptionId(prescription.getId());//设置药方id
            detail.setPatientId(data.get(0).getPid());//设置病人id
            detail.setRegistryId(data.get(0).getRid());//设置挂号单id
            detail.setDrugId(item.getId());//设置药品id
            detail.setAmount(item.getNum());//药品数量
            detailMapper.add(detail);//药方明细表添加记录，返回药方明细id
            PrescriptionBatchDetail batchDetail = new PrescriptionBatchDetail();
            batchDetail.setPrescriptionDetailId(detail.getId());//设置药品明细id
            batchDetail.setDrugBatchId(item.getBatch());//设置药品批次id
            batchDetail.setUsedAmount(item.getNum());//用药数量
            int n = batchDetailMapper.add(batchDetail);//药方批次添加记录
        });
        return id;
    }

    @Override
    public List<PrescriptionVo> findAll(PrescriptionDto dto) {
        return mapper.findAll(dto);
    }



    @Override
    public List<PrescriptionDrugVo> findPrescriptionDrug(Integer id) {
        return prescriptionDrugMapper.findAll(id);
    }

    @Override
    public int getCount(PrescriptionDto dto) {
        return mapper.getCount(dto);
    }

    @Override
    public int getDrug(List<PrescriptionDrugVo> vo) {
        //更新药方状态
        int a =  mapper.updateIsFetchMedicine(vo.get(0).getPid());
        //更新药方对应的每种药品批次剩余库存
        vo.forEach(item->{
            drugBatchMapper.updateResidueStock(item);
        });
        return a;
    }
}
